package com.base.maintain;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;

/**
 * @author yanjiaqiang
 * @date 2010-12-31
 * @version $Id: LogExtractTask.java 7 2011-07-15 04:24:04Z JiaqiangYan@gmail.com $
 */
public class LogExtractTask implements Runnable {

	private File logFile;

	private File toFile;

	private StringMatcher matcher;

	public LogExtractTask(File logFile, File toFile, StringMatcher matcher) {
		super();
		this.logFile = logFile;
		this.toFile = toFile;
		this.matcher = matcher;
	}

	@Override
	public void run() {
		extract(logFile, toFile);
	}

	private void extract(File file, File toFile) {
		if (file.isFile()) {
			extractFile(file, toFile);
		}
		File[] files = file.listFiles();
		if (files != null) {
			for (File f : files) {
				extract(f, toFile);
			}
		}
	}

	private void extractFile(File f, File toFile) {
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new FileReader(f));
			bw = new BufferedWriter(new FileWriter(toFile, true));

			String line = null;
			StringBuilder sb = new StringBuilder(1024 * 1024 * 10);
			while ((line = br.readLine()) != null) {
				List<String> list = matcher.match(line);
				if (CollectionUtils.isNotEmpty(list)) {
					sb.append(list.get(0));
					for (int i = 1; i < list.size(); i++) {
						sb.append(" || " + list.get(i));
					}
					sb.append("\r\n");
				}

			}
			bw.write(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(br);
			IOUtils.closeQuietly(bw);
		}
	}
}
